"use client";
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "@/app/ui/components/ui/dialog";
import { memo, useCallback } from "react";
import ReactJson from 'react-json-view';

type JsonViewDialogProps = {
    title?: string,
    value?: string,
    onChange?: (val: string) => void,
    children?: React.ReactNode,
    isDialog?: boolean
}

export default memo(function JsonViewDialog({ title, value, onChange, children, isDialog }: JsonViewDialogProps) {
    const onValueChange = useCallback((val: any) => {
        onChange && onChange(JSON.stringify(val?.updated_src));
        return val?.updated_src
    }, [onChange])
    return <>
        {
            isDialog ? (
                <Dialog>
                    <DialogTrigger asChild>{children}</DialogTrigger>
                    <DialogContent>
                        <DialogHeader>
                            <DialogTitle>{title}</DialogTitle>
                        </DialogHeader>
                        <ReactJson src={JSON.parse(value || '{}')} onEdit={onValueChange} onAdd={onValueChange} onDelete={onValueChange} />
                    </DialogContent>
                </Dialog>
            ) : (
                <ReactJson src={JSON.parse(value || '{}')} onEdit={onValueChange} onAdd={onValueChange} onDelete={onValueChange} />
            )
        }
    </>
})